package com.yang.service.impl;

import com.yang.domain.LoginUser;
import com.yang.domain.User;
import com.yang.service.LoginService;
import com.yang.utils.JwtUtil;
import com.yang.utils.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    private static Map<String, Object> userMap = new HashMap<>();

    @Override
    public Map<String, String> login(User user) {
        // AuthenticationManager的authenticate方法进行认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        // 如果认证没有通过，给出对应提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }

        // 如果认证通过了，使用userId生成一个JWT，JWT存入ResponseResult返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);

        Map<String, String> result = new HashMap<>();
        result.put("token", jwt);

        // 把完整的用户信息存入Redis，userId作为key
        userMap.put("login:" + userId, loginUser);

        return result;
    }

    /**
     * 退出登录接口
     */
    @Override
    public void logout() {
        // 获取SecurityContextHolder中的用户ID
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        // 删除Redis中的值
        redisCache.deleteObject("login:" + userId);
    }

}
